package personal.wang.juc;

import java.io.IOException;
import java.util.concurrent.CompletableFuture;

public class CompletableFutureTest4 {
    public static void main(String[] args) {
//        CompletableFuture<Integer> integerCompletableFuture = CompletableFuture.supplyAsync(() -> {
//            try {
//                Thread.sleep(4000L);
//            } catch (InterruptedException e) {
//                throw new RuntimeException(e);
//            }
//            return 1;
//        });
//
//        integerCompletableFuture
//                .handle((record ,throwable) -> {
//                     System.out.println("throwable: " + throwable);
//                    System.out.println("record: " + record);
//                     return record ;
//                });
//
//        integerCompletableFuture.cancel(true);
//

        CompletableFuture<Integer> cf1 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(2000L);
                System.out.println("cf1 complete");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return 1;
        });

        CompletableFuture<Integer> cf2 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(3000L);
                System.out.println("cf2 complete");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return 2;
        });

        CompletableFuture<Integer> cf3 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(4000L);
                System.out.println("cf3 complete");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return 3;
        });
        CompletableFuture<Object> anyOf = CompletableFuture.anyOf(new CompletableFuture[]{cf1, cf2, cf3});
        anyOf.thenAccept((none) -> {
            System.out.println("allOf run");
            System.out.println(none);
            cf2.completeExceptionally(new RuntimeException("test"));
            cf3.completeExceptionally(new RuntimeException("test2"));
            System.out.println(cf1.join());
            System.out.println("------");
            cf2.handle((r , th) -> {
                System.out.println(th.getMessage());
                return 0 ;
            });

            cf3.handle((r , th) -> {
                System.out.println(th.getMessage());
                return 0 ;
            });
        });
        try {
            System.in.read();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
